import pandas as pd
from flask import Flask, render_template
import jieba
from collections import Counter
from pyecharts.charts import Line,Pie,Scatter,Bar,Map,Grid
from pyecharts.charts import WordCloud
from pyecharts import options as opts
from pyecharts.globals import ThemeType
from pyecharts.globals import SymbolType
from pyecharts.commons.utils import JsCode

app = Flask(__name__)

@app.route('/')
def hello_world():  # put application's code here
    return render_template('index2.html'
                           )


@app.route('/a')
def a() -> 'html':
    df = pd.read_excel(r'static/data/旅游景点.xlsx')
    color_js = """new echarts.graphic.LinearGradient(0, 0, 1, 0,
        [{offset: 0, color: '#009ad6'}, {offset: 1, color: '#ed1941'}], false)"""
    sort_info = df.sort_values(by='销量', ascending=True)
    a = (
        Bar()
            .add_xaxis(list(sort_info['名称'])[-20:])
            .add_yaxis('热门景点销量', sort_info['销量'].values.tolist()[-20:],
                       itemstyle_opts=opts.ItemStyleOpts(color=JsCode(color_js)))
            .reversal_axis()
            .set_global_opts(
            title_opts=opts.TitleOpts(title='热门景点销量数据'),
            yaxis_opts=opts.AxisOpts(name='景点名称'),
            xaxis_opts=opts.AxisOpts(name='销量'),
        )
            .set_series_opts(label_opts=opts.LabelOpts(position="right"))

    )
    a.render("templates/popular.html")
    with open("templates/popular.html", encoding="utf8", mode="r") as f:
        plot_a = "".join(f.readlines())
    return render_template(
        'index.html',rl=plot_a,base='active',wz='可以看出上海迪士尼和上海海昌海洋公园的销量最高且与第三名差距较大，如果想去热门景点则可以选择图上前20景点，若是想要避开人流量大的景点则最好不要选择以上景点。'
    )

@app.route('/h')
def h() -> 'html':
    df = pd.read_excel(r'static/data/旅游景点.xlsx')
    color_js = """new echarts.graphic.LinearGradient(0, 0, 1, 0,
        [{offset: 0, color: '#009ad6'}, {offset: 1, color: '#ed1941'}], false)"""

    sort_info = df.sort_values(by='销量', ascending=True)
    a = (
        Bar()
            .add_xaxis(list(sort_info['名称'])[-20:])
            .add_yaxis('热门景点价格', sort_info['价格'].values.tolist()[-20:],
                       itemstyle_opts=opts.ItemStyleOpts(color=JsCode(color_js)))
            .reversal_axis()
            .set_global_opts(
            title_opts=opts.TitleOpts(title='热门景点价格数据'),
            yaxis_opts=opts.AxisOpts(name='景点名称'),
            xaxis_opts=opts.AxisOpts(name='价格'),
        )
            .set_series_opts(label_opts=opts.LabelOpts(position="right"))
    )
    a.render("templates/popular.html")
    with open("templates/popular.html", encoding="utf8", mode="r") as f:
        plot_a = "".join(f.readlines())
    return render_template(
        'index.html',rl=plot_a,base='active',wz='销量前20的景点门票价格相差较大，可以根据自己的需求进行筛选。'
    )



@app.route('/b', methods=['GET'])
def b() -> 'html':
    df = pd.read_excel(r'static/data/旅游景点.xlsx')
    df_tmp1 = df[['城市', '销量']]
    df_counts = df_tmp1.groupby('城市').sum()
    a = (
        Map()
            .add("假期出行分布", [list(z) for z in zip(df_counts.index.values.tolist(), df_counts.values.tolist())], "china")
        .set_global_opts(
        title_opts=opts.TitleOpts(title="假期出行数据地图分布"),
        visualmap_opts=opts.VisualMapOpts(max_=100000, is_piecewise=False,
                                          range_color=["white", "#fa8072", "#ed1941"]),
    )
    )
    a.render('templates/map1.html')
    with open("templates/map1.html", encoding="utf8", mode="r") as f:
        plot_a = "".join(f.readlines())
    return render_template(
        'index.html',rl=plot_a,b='active',wz='北京、上海、广东、四川、陕西是最热门的几大旅游省市，如果不想去人流过多的旅游景点，可以避开以上省市。'
    )

@app.route('/c', methods=['GET'])
def c() -> 'html':
    df = pd.read_excel(r'static/data/旅游景点.xlsx')
    df_tmp2 = df[df['星级'].isin(['4A', '5A'])]
    df_counts = df_tmp2.groupby('城市').count()['星级']
    item_style = {'normal': {'shadowColor': '#000000',
                             'shadowBlur': 20,
                             'shadowOffsetX': 5,
                             'shadowOffsetY': 15
                             }
                  }
    a = (
        Scatter()
            .add_xaxis(df_counts.index.values.tolist())
            .add_yaxis('4A-5A景区数量', df_counts.values.tolist(), symbol_size=50, itemstyle_opts=item_style)
            .set_global_opts(visualmap_opts=opts.VisualMapOpts(is_show=False,
                                                               type_='size',
                                                               range_size=[5, 50]))
        #         .render("4A.html")
    )
    a.render('templates/4A.html')
    with open("templates/4A.html", encoding="utf8", mode="r") as f:
        plot_a = "".join(f.readlines())
    return render_template(
        'index.html',rl=plot_a,c='active',wz='江苏、安徽4A、5A级景区数量并列第一，如果想要去4A、5A级景区可以优先考虑这两个省。'
    )

@app.route('/d', methods=['GET'])
def d() -> 'html':
    df = pd.read_excel(r'static/data/旅游景点.xlsx')
    df_tmp3 = df[df['星级'].isin(['4A', '5A'])]
    df_counts = df_tmp3.groupby('城市').count()['星级']
    a = (
        Map()
            .add('4A-5A景区分布', [list(z) for z in zip(df_counts.index.values.tolist(), df_counts.values.tolist())],
                 'china')
            .set_global_opts(
            title_opts=opts.TitleOpts(title='地图数据分布'),
            visualmap_opts=opts.VisualMapOpts(max_=50, is_piecewise=True),
        )
    )
    a.render('templates/4Amap.html')
    with open("templates/4Amap.html", encoding="utf8", mode="r") as f:
        plot_a = "".join(f.readlines())
    return render_template(
        'index.html',rl=plot_a,d='active',wz='从地图可以看出，除了江苏、安徽外，河南、北京、湖北等地区4A、5A级景区数量也较多。'
    )

@app.route('/e', methods=['GET'])
def e() -> 'html':
    df = pd.read_excel(r'static/data/旅游景点.xlsx')
    price_level = [0, 50, 100, 150, 200, 250, 300, 350, 400, 500]
    label_level = ['0-50', '50-100', '100-150', '150-200', '200-250', '250-300', '300-350', '350-400', '400-500']
    jzmj_cut = pd.cut(df['价格'], price_level, labels=label_level)
    df_price = jzmj_cut.value_counts()
    df_price
    a = (
        Pie(init_opts=opts.InitOpts(
            width='800px', height='600px',
        )
        )
            .add(
            '',
            [list(z) for z in zip(df_price.index.tolist(), df_price.values.tolist())],
            radius=['20%', '60%'],
            center=['40%', '50%'],
            rosetype='radius',
            label_opts=opts.LabelOpts(is_show=True),
        )
            .set_global_opts(title_opts=opts.TitleOpts(title='门票价格占比', pos_left='33%', pos_top="5%"),
                             legend_opts=opts.LegendOpts(type_='scroll', pos_left="80%", pos_top="25%",
                                                         orient="vertical")
                             )
            .set_series_opts(label_opts=opts.LabelOpts(formatter='{b}: {c} ({d}%)'), position='outside')
    )
    a.render('templates/price.html')
    with open("templates/price.html", encoding="utf8", mode="r") as f:
        plot_a = "".join(f.readlines())
    return render_template(
        'index.html',rl=plot_a,e='active',wz='门票价格100以内居多，大概占比70%，还是比较实惠的。'
    )

@app.route('/f', methods=['GET'])
def f() -> 'html':
    df = pd.read_excel(r'static/data/旅游景点.xlsx')
    price_level = [0, 50, 100, 150, 200, 250, 300, 350, 400, 500]
    label_level = ['0-50', '50-100', '100-150', '150-200', '200-250', '250-300', '300-350', '350-400', '400-500']
    jzmj_cut = pd.cut(df['价格'], price_level, labels=label_level)
    df_price = jzmj_cut.value_counts()
    df_price
    color_js = """new echarts.graphic.RadialGradient(
                        0.5, 0.5, 1,
                        [{offset: 0,
                          color: '#009ad6'},
                         {offset: 1,
                          color: '#ed1941'}
                          ])"""

    a = (
        Scatter()
            .add_xaxis(df_price.index.tolist())
            .add_yaxis('门票价格区间', df_price.values.tolist(), symbol_size=50,
                       itemstyle_opts=opts.ItemStyleOpts(color=JsCode(color_js)))
            .set_global_opts(
            yaxis_opts=opts.AxisOpts(name='数量'),
            xaxis_opts=opts.AxisOpts(name='价格区间(元)'))
            .set_global_opts(visualmap_opts=opts.VisualMapOpts(is_show=False,
                                                               # 设置通过图形大小来表现数据
                                                               type_='size',
                                                               # 图形大小映射范围
                                                               range_size=[5, 50]))
    )
    a.render('templates/price2.html')
    with open("templates/price2.html", encoding="utf8", mode="r") as f:
        plot_a = "".join(f.readlines())
    return render_template(
        'index.html',rl=plot_a,f='active',wz='价格区间分布大致为门票越贵的景点数量越少。'
    )

@app.route('/g', methods=['GET'])
def g() -> 'html':
    df = pd.read_excel(r'static/data/旅游景点.xlsx')
    contents = "".join('%s' % i for i in df['简介'].values.tolist())
    contents_list = jieba.cut(contents)
    ac = Counter(contents_list)

    stopwords = []
    with open('stopwords.txt', "r", encoding='utf-8') as f:  # 打开文件
        data = f.read()  # 读取文件
        stopwords = data.split('\n')

    for i in stopwords:
        del ac[i]

    a = (
        WordCloud()
            .add(
            "",
            ac.most_common(200),
            word_size_range=[5, 80],
            textstyle_opts=opts.TextStyleOpts(font_family="cursive"),
            mask_image='image/1.jpg'
        )
            .set_global_opts(
            title_opts=opts.TitleOpts(title="自定义样式词云图"),
        )
    )
    a.render('templates/wordcloud.html')
    with open("templates/wordcloud.html", encoding="utf8", mode="r") as f:
        plot_a = "".join(f.readlines())
    return render_template(
        'index.html',rl=plot_a,g='active',wz='各个景点的简介关键词中“文化”一次出现的频率最高。'
    )


if __name__ == '__main__':
    app.run()